//
//  DHAlertView.m
//  测试、
//
//  Created by 董浩 on 15/11/30.
//  Copyright © 2015年 董浩. All rights reserved.
//

#import "DHAlertView.h"
#import "Config.h"
//#import "UIView+EXT.h"

typedef void(^TouchAlertBlock)();

@interface DHAlertView ()<UIGestureRecognizerDelegate>
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *message;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *destructiveButton;
@property (nonatomic, assign) CGFloat titleHeight;
@property (nonatomic, assign) CGFloat messageHeight;
@property (nonatomic, assign) CGFloat contentViewHeight;
@property (nonatomic, assign) CGFloat buttonHeight;
@property (nonatomic, assign) CGFloat setHeight;
@property (nonatomic, copy) TouchAlertBlock touchAlertBlock;

@end

static NSString *const kTitle = @"title";
static NSString *const kColor = @"color";

@implementation DHAlertView

- (void)addCancelButtonWithTitle:(NSString *)cancel block:(void (^)())cancelBlock destructiveButtonWithTitle:(NSString *)destructive block:(void (^)())destructiveBlock {
    
    if (!cancel && !destructive) {
        return;
    }
    
    _buttonHeight = 30.0f;
    
    if (cancel) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _cancelButton.layer.cornerRadius = 5;
        _cancelButton.layer.masksToBounds = YES;
        _cancelButton.layer.shouldRasterize = YES;
        _cancelButton.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [_cancelButton setTitle:cancel forState:UIControlStateNormal];
        [_cancelButton setBackgroundColor:[UIColor lightGrayColor]];
        [_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_contentView addSubview:_cancelButton];
    }
    
    if (cancelBlock) {
        _cancelBlock = cancelBlock;
    }
    
    if (destructive) {
        _destructiveButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _destructiveButton.layer.cornerRadius = 5;
        _destructiveButton.layer.masksToBounds = YES;
        _destructiveButton.layer.shouldRasterize = YES;
        _destructiveButton.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [_destructiveButton setTitle:destructive forState:UIControlStateNormal];
        [_destructiveButton setBackgroundColor:[UIColor redColor]];
        [_destructiveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_destructiveButton addTarget:self action:@selector(destructiveButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_contentView addSubview:_destructiveButton];
    }
    
    if (destructiveBlock) {
        _destructiveBlock = destructiveBlock;
    }
    
    [self setButtonLayoutWithCancel:cancel destructive:destructive];
    [self recalcContentHeight];
}

- (void)setButtonLayoutWithCancel:(NSString *)cancel destructive:(NSString *)destructive {
    
    CGFloat width = 270 / WIDTH_5S_SCALE / 2 - 30.0f;
    CGFloat height = 25.0f;
    CGFloat top = _contentView.frame.size.height;
    NSLog(@"%f",_contentView.frame.size.height);
    
    if (cancel && destructive) {
        _cancelButton.frame = CGRectMake(20, top, width, height);
        _destructiveButton.frame = CGRectMake(width + 40, top, width, height);
        return;
    }
    
    if (!cancel && !destructive) {
        return;
    }
    
    if (cancel) {
        _cancelButton.frame = CGRectMake(270 / WIDTH_5S_SCALE / 4 + 16.5f, top, width, height);
    }
    
    if (destructive) {
        _destructiveButton.frame = CGRectMake(270 / WIDTH_5S_SCALE / 4 + 16.5f, top, width, height);
    }
}

+ (DHAlertView *)alertViewWithTitle:(NSString *)title message:(NSString *)message {
    return [[DHAlertView alloc] initWithTitle:title message:message];
}

- (id)initWithContentHeight:(CGFloat)height {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];

    if (self) {
        _titleHeight = 0.0f;
        _messageHeight = 0.0f;
        _buttonHeight = 0.0f;
        _setHeight = height;
        _contentViewHeight = _titleHeight + _messageHeight + _buttonHeight + _setHeight + 5.0f;
        
        [self cteateContentView];
        _contentView.frame = CGRectMake((SCREEN_WIDTH - 270 / WIDTH_5S_SCALE) / 2 , (SCREEN_HEIGHT - _contentViewHeight) / 2 - 15, 270 / WIDTH_5S_SCALE, _contentViewHeight);

        
    }
    return self;
}

- (id)initWithTitle:(NSString *)title message:(NSString *)message {
    
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    
    if (self) {
        _titleHeight = 30.0f;
        _messageHeight = 30.0f;
        _buttonHeight = 0.0f;
        _setHeight = 0.0f;
        _contentViewHeight = _titleHeight + _messageHeight + _buttonHeight + _setHeight;
        
        _title = [title copy];
        _message = [message copy];
        
        [self _initSubViews];
        
        [self setupDisPlay];
        [self setContent];
    }
    
    return self;
}

- (void)cteateContentView {
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disMiss)];
    tap.numberOfTapsRequired = 1;
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    
    self.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
    
    _contentView = [UIView new];
    _contentView.backgroundColor = [UIColor whiteColor];
    _contentView.layer.cornerRadius = 5.0f;
    _contentView.layer.masksToBounds = YES;
    _contentView.layer.shouldRasterize = YES;
    _contentView.layer.rasterizationScale = [UIScreen mainScreen].scale;
    
    [self addSubview:_contentView];
}

- (void)_initSubViews {
    [self cteateContentView];
    
    _titleLabel = [UILabel new];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.font = DEF_FontSize_14;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_contentView addSubview:_titleLabel];
    
    _messageLabel = [UILabel new];
    _messageLabel.font = DEF_FontSize_11;
    _messageLabel.numberOfLines = 0;
    _messageLabel.textAlignment = NSTextAlignmentCenter;
    _messageLabel.textColor = [UIColor blackColor];
    [_contentView addSubview:_messageLabel];
}

- (void)recalcContentHeight {
    _contentViewHeight = _titleHeight + _messageHeight + _buttonHeight + _setHeight + 15.0f;
    [self setupDisPlay];
}

- (void)setupDisPlay {
    _contentView.frame = CGRectMake((SCREEN_WIDTH - 270 / WIDTH_5S_SCALE) / 2 , (SCREEN_HEIGHT - _contentViewHeight) / 2 - 15, 270 / WIDTH_5S_SCALE, _contentViewHeight);
    
    _titleLabel.frame = CGRectMake(5, 5, _contentView.frame.size.width - 10, _titleHeight);
    
    _messageLabel.frame  = CGRectMake(5, _titleHeight + 5, _contentView.frame.size.width - 10, _messageHeight);
    
}

- (void)setContent {
    _titleLabel.text = _title;
    
    _messageLabel.text = _message;
    [_messageLabel sizeToFit];
    _messageHeight = _messageLabel.frame.size.height;
    [self recalcContentHeight];
}

- (void)cancelButtonClick:(UIButton *)cancelBtn {
    if (_cancelBlock) {
        _cancelBlock(cancelBtn);
    }
    [self disMiss];
}

- (void)destructiveButtonClick:(UIButton *)destructiveButton {
    if (_destructiveBlock) {
        _destructiveBlock(destructiveButton);
    }
    [self disMiss];
}

- (id)initTouchAlertWithContentHeight:(CGFloat)height actionBlock:(void(^)())block {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    
    if (self) {
        _titleHeight = 0.0f;
        _messageHeight = 0.0f;
        _buttonHeight = 0.0f;
        _setHeight = height;
        _contentViewHeight = _titleHeight + _messageHeight + _buttonHeight + _setHeight + 5.0f;
        
        self.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
        
        _contentView = [UIView new];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.cornerRadius = 5.0f;
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.shouldRasterize = YES;
        _contentView.layer.rasterizationScale = [UIScreen mainScreen].scale;
        
        [self addSubview:_contentView];
        
        _contentView.frame = CGRectMake((SCREEN_WIDTH - 270 / WIDTH_5S_SCALE) / 2 , (SCREEN_HEIGHT - _contentViewHeight) / 2 - 15, 270 / WIDTH_5S_SCALE, _contentViewHeight);
        
        self.touchAlertBlock = block;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchAlertAction)];
        tap.numberOfTapsRequired = 1;
//        tap.delegate = self;
        [_contentView addGestureRecognizer:tap];
        __weak __typeof(self)weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.41 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf touchAlertAction];
        });
    }
    return self;
}

- (void)touchAlertAction {
    [self disMiss];
    if (self.touchAlertBlock) {
        self.touchAlertBlock();
    }
    [self setTouchAlertBlock:nil];
}

#pragma mark -
#pragma mark - Animation

- (void)show {
    [[[UIApplication sharedApplication].delegate window] addSubview:self];
    [DHAlertView exChangeOut:_contentView dur:0.5];
}

- (void)disMiss {
    [self removeFromSuperview];
}

+ (void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur {
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    
    animation.duration = dur;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    
    [changeOutView.layer addAnimation:animation forKey:nil];
}


#pragma mark -
#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return [self judgeTouchInView:touch.view superView:_contentView];
}

- (BOOL)judgeTouchInView:(UIView *)touchView superView:(UIView *)superView {
    
    if ([touchView isEqual:superView]) {
        return NO;
    }
    
    __block BOOL flag = YES;
    
    if (superView.subviews) {
        [superView.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
            flag = [self judgeTouchInView:touchView superView:obj];
        }];
    }
    return flag;
}


@end
